package top.yaofengqiao.springcloudsimple.auth.biz.domain.security.service;

import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.oauth2.provider.ClientDetails;
import org.springframework.security.oauth2.provider.ClientDetailsService;
import org.springframework.security.oauth2.provider.ClientRegistrationException;
import org.springframework.stereotype.Component;
import top.yaofengqiao.springcloudsimple.auth.biz.domain.security.model.Client;
import top.yaofengqiao.springcloudsimple.auth.biz.domain.security.model.ClientInfo;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

/**
 * @author yfq
 * @date 2024/5/31 15:20
 * @description 获取客户端信息
 */
@Component
public class ClientDetailServiceImpl implements ClientDetailsService {
    private final List<Client> clientList = new ArrayList<>();

    @Resource
    private PasswordEncoder passwordEncoder;

    // TODO 从数据库获取客户端信息
    @PostConstruct
    public void initData() {
        String clientSecret = passwordEncoder.encode("123456");
        // 1、密码模式
        clientList.add(Client.builder()
                .clientId("client-app")
                .resourceIds("oauth2-resource")
                .secretRequire(false)
                .clientSecret(clientSecret)
                .scopeRequire(false)
                .scope("all")
                .authorizedGrantTypes("password,refresh_token")
                .authorities("admin,user")
                .accessTokenValidity(3600)
                .refreshTokenValidity(86400).build());
        // 2、授权码模式
        clientList.add(Client.builder()
                .clientId("client-app-2")
                .resourceIds("oauth2-resource2")
                .secretRequire(false)
                .clientSecret(clientSecret)
                .scopeRequire(false)
                .scope("all")
                .authorizedGrantTypes("authorization_code,refresh_token")
                .webServerRedirectUri("https://www.gathub.cn,https://www.baidu.com")
                .authorities("USER")
                .accessTokenValidity(3600)
                .refreshTokenValidity(86400).build());
    }

    @Override
    public ClientDetails loadClientByClientId(String clientId) throws ClientRegistrationException {
        Optional<Client> first = clientList.stream().filter(client -> client.getClientId().equals(clientId)).findFirst();

        Client client = first.orElse(null);

        if (client == null) return null;

        return new ClientInfo(client);
    }

}
